import {
  OnInit,
  OnChanges,
  OnDestroy,
  Component,
  ChangeDetectionStrategy,
  ViewEncapsulation,
  Input,
  TemplateRef,
  NgZone,
  ViewChild,
  ElementRef,
} from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Lbchart } from '@shared';
import { Subscription } from 'rxjs';
/**
 * 基础热力图
 */
@Component({
  selector: 'lb-basic-heatmap',
  template: `
    <div #basicheatmap></div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbBasicHeatmapComponent
  implements OnInit, OnChanges, OnDestroy, Lbchart {
  private chart: any;
  private resize$: Subscription;
  @ViewChild('basicheatmap', { static: true }) private node: ElementRef;
  @Input() padding: Array<number | string> | string = 'auto';
  @Input() @InputNumber() delay = 0;
  @Input() color: string[] = null;
  @Input() colorFiled = 'name';
  @Input() position: any;
  @Input() data: any[];
  @Input() height: number;

  @Input() @InputBoolean() tooltipshow;
  @Input() @InputBoolean() tooltipshowtitle;

  @Input() sortx = true
  @Input() sortz
  @Input() sortrule = 'ASC'

  constructor(private ngZone: NgZone) {}

  commonStyleHandle(chart, data) {
    const dv = new DataSet.View().source(data);

    // if(this.sortx && !this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,        // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(!this.sortx && this.sortz){
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // } else if(this.sortx && this.sortz) {
    //   dv.transform({
    //     type: 'sort-by',
    //     fields: [ this.sortx, this.sortz ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
    //     order: this.sortrule,   // 默认为 ASC，DESC 则为逆序
    //   })
    // }    

    chart.source(dv.rows);

    chart.axis(this.position.x, {
      tickLine: null,
      grid: {
        align: 'center',
        lineStyle: {
          lineWidth: 1,
          lineDash: null,
          stroke: '#f0f0f0',
        },
      },
    });
    chart.axis(this.position.z, {
      title: null,
      grid: {
        align: 'center',
        lineStyle: {
          lineWidth: 1,
          lineDash: null,
          stroke: '#f0f0f0',
        },
        showFirstLine: true,
      },
    });

    if (this.tooltipshow) {
      chart.tooltip({
        showTitle: this.tooltipshowtitle,
        itemTpl: '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
      });
    } else {
      chart.tooltip(false);
    }

    return dv.rows
  }

  install() {
    //   this.data =
    //       [
    //   { genre: 'Sports', sold: 275, type: '一年级' },
    //   { genre: 'Sports', sold: 215, type: '二年级' },
    //   { genre: 'Sports', sold: 245, type: '三年级' },
    //   { genre: 'Strategy', sold: 243, type: '一年级' },
    //   { genre: 'Strategy', sold: 143, type: '二年级' },
    //   { genre: 'Strategy', sold: 223, type: '三年级' },
    //   { genre: 'Action', sold: 127, type: '一年级' },
    //   { genre: 'Action', sold: 431, type: '二年级' },
    //   { genre: 'Action', sold: 320, type: '三年级' },
    //   { genre: 'Shooter', sold: 350, type: '一年级' },
    //   { genre: 'Shooter', sold: 150, type: '二年级' },
    //   { genre: 'Shooter', sold: 250, type: '三年级' },
    //   { genre: 'Other', sold: 114, type: '一年级' },
    //   { genre: 'Other', sold: 67, type: '二年级' },
    //   { genre: 'Other', sold: 276, type: '三年级' },
    // ];
    // this.position =  { x: 'genre', y: 'type', z: 'sold' }
    this.render();
  }

  render() {
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true, // 图表的宽度自适应开关
      height: this.getHeight(),
      padding,
    }));

    this.commonStyleHandle(chart, this.data);

    chart
      .polygon()
      .position(`${this.position.x}*${this.position.z}`)
      .color(`${this.position.y}`, '#BAE7FF-#1890FF-#0050B3')
      .label(`${this.position.y}`, {
        offset: -2,
        textStyle: {
          fill: '#fff',
          shadowBlur: 2,
          shadowColor: 'rgba(0, 0, 0, .45)',
        },
      })
      .style({
        lineWidth: 1,
        stroke: '#fff',
      });

    // Step 4: 渲染图表
    chart.render();
  }

  attachChart() {
    const { chart, padding, data, color } = this;
    if (!chart || !data || data.length <= 0) return;
    const height = this.getHeight();
    if (chart.get('height') !== height) {
      chart.changeHeight(height);
    }

  const dvrows =   this.commonStyleHandle(chart, this.data)
    // color
    //  chart.get('geoms')[0].color(this.colorFiled,this.color);
    chart.set('padding', padding);
    chart.changeData(dvrows);
  }

  destroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
  getHeight() {
    return this.height;
    // return this.title ? (this.height - TITLE_HEIGHT) : this.height;
  }

  ngOnInit(): void {
    if (this.position && this.data.length > 0) {
      this.ngZone.runOutsideAngular(() =>
        setTimeout(() => this.install(), this.delay),
      );
    }
  }

  ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.attachChart());
  }
  ngOnDestroy(): void {
    this.destroy();
  }
}
